package com.hctforgreen.greenservice;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.HttpAuthHandler;
import android.webkit.WebSettings;
import android.webkit.WebSettings.TextSize;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.LinearLayout;

import com.hctforgreen.greenservice.utils.AsyncImageLoader;
import com.hctforgreen.greenservice.utils.AsyncImageLoader.ImageCallback;
import com.hctforgreen.greenservice.utils.HctConstants;
import com.hctforgreen.greenservice.utils.Md5Util;
import com.hctforgreen.greenservice.utils.ThemeStoreUtil;

/**
 * 展示大图的页面
 * 
 * @author Tallen Zhai
 * 
 */
public class ShowMegaImageActivity extends ParentActivity {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_show_mega_image);
		initSkinLayout();
		initWindow();

	}


	private void initWindow() {
		String path = getIntent().getStringExtra(
				HctConstants.ON_ACTIVITY_KEY_MEGE_IMAGE_PATH);

		final WebView webView = (WebView) findViewById(R.id.wv_contents);

		initWebView(webView);
		initLoadLayoutClick();
		if (path.startsWith("file://")) {
			renderWebView(webView, path);
			final LinearLayout loadLyt = (LinearLayout) findViewById(R.id.lyt_default_load);
			loadLyt.setVisibility(View.GONE);
		} else if (path.startsWith("http://")) {

			loadImage(path, webView);
		}

	}

	private void loadImage(final String path, final WebView webView) {
		final LinearLayout loadLyt = (LinearLayout) findViewById(R.id.lyt_default_load);
		final LinearLayout reLoadLyt = (LinearLayout) findViewById(R.id.lyt_default_reload);

		final Button reLoadBtn = (Button) findViewById(R.id.btn_default_reload);
		final String sCacheUrl = HctConstants.DEFAULT_ROOT_PATH
				+ HctConstants.DEFAULT_CACHE_STORE_PATH + Md5Util.md5(path);

		AsyncImageLoader imageLoader = new AsyncImageLoader();
		Drawable cacheDrawable = imageLoader.loadDrawable(path,
				ShowMegaImageActivity.this, true, new ImageCallback() {

					@Override
					public void imageLoaded(Drawable imageDrawable,
							String imageUrl) {
						if (imageDrawable != null) {
							renderWebView(webView, "file://" + sCacheUrl);
							loadLyt.setVisibility(View.GONE);
						} else {
							loadLyt.setVisibility(View.GONE);
							reLoadLyt.setVisibility(View.VISIBLE);
							reLoadBtn.setOnClickListener(new OnClickListener() {

								@Override
								public void onClick(View v) {
									loadImage(path, webView);
								}
							});
						}

					}
				});
		if (cacheDrawable != null) {
			renderWebView(webView, "file://" + sCacheUrl);
			loadLyt.setVisibility(View.GONE);
			reLoadLyt.setVisibility(View.GONE);
		} else {
			loadLyt.setVisibility(View.VISIBLE);
			reLoadLyt.setVisibility(View.GONE);
		}
	}

	private void initLoadLayoutClick() {
		final LinearLayout loadLyt = (LinearLayout) findViewById(R.id.lyt_default_load);
		loadLyt.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});
	}

	private void renderWebView(final WebView webView, final String path) {

		StringBuilder sHtml = makeHtmlContent(path);

		webView.loadDataWithBaseURL(null, sHtml.toString(), "text/html",
				"uft-8", null);

	}

	@SuppressLint("JavascriptInterface")
	private WebView initWebView(WebView webView) {

		webView.setBackgroundColor(0); // 设置背景色

		// 取消滚动条
		webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
		webView.setWebViewClient(mWebViewClient);

		webView.requestFocus(View.FOCUS_DOWN);
		webView.getSettings().setBlockNetworkImage(false);
		webView.getSettings().setSupportZoom(true);
		webView.getSettings().setDefaultTextEncodingName("UTF-8");
		webView.getSettings().setBuiltInZoomControls(true);

		webView.getSettings().setJavaScriptEnabled(true);
		webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
		// webView.getSettings().setPluginsEnabled(true);
		webView.getSettings().setPluginState(WebSettings.PluginState.ON);
		webView.getSettings().setSupportMultipleWindows(true);
		webView.getSettings().setTextSize(TextSize.NORMAL);

		webView.getSettings().setSaveFormData(false);
		webView.getSettings().setSavePassword(false);
		webView.getSettings().setUseWideViewPort(true);
		webView.setSaveEnabled(false);
		webView.clearCache(true);
		webView.addJavascriptInterface(new JavascriptInterface(
				ShowMegaImageActivity.this), "onBodyClickListner");
		return webView;
	}

	private StringBuilder makeHtmlContent(final String path) {
		StringBuilder sHtml = new StringBuilder();
		sHtml.append("<head>");
		sHtml.append("<meta name=\"viewport\" content=\"width=device-width,height=device-height, initial-scale=1.0, minimum-scale=0.5, maximum-scale=4.0, user-scalable=yes\" />");
		sHtml.append("</head>");
		sHtml.append("<body style=\"width:100%;height:100%;border:0;margin:0;padding:0;\">");
		sHtml.append("<table style=\"width:100%;height:100%;\">");
		sHtml.append("<tr>");
		sHtml.append("<td align=\"center\" valign=\"middle\">");
		sHtml.append("<img style=\"width:100%;height:auto;\" src='");
		sHtml.append(path);
		sHtml.append("'>");
		sHtml.append("</td>");
		sHtml.append("</tr>");
		sHtml.append("</table>");
		sHtml.append("</body>");
		return sHtml;
	}

	private WebViewClient mWebViewClient = new WebViewClient() {
		@Override
		public void onReceivedError(WebView view, int errorCode,
				String description, String failingUrl) {
			super.onReceivedError(view, errorCode, description, failingUrl);
		}

		@Override
		public void onReceivedHttpAuthRequest(WebView view,
				HttpAuthHandler handler, String host, String realm) {
			super.onReceivedHttpAuthRequest(view, handler, host, realm);
		}

		@Override
		public void onLoadResource(WebView view, String url) {
			super.onLoadResource(view, url);
		}

		@Override
		public void onPageFinished(WebView view, String url) {
			super.onPageFinished(view, url);
			addImageClickListner(view);
		}

		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			super.onPageStarted(view, url, favicon);
		}

		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {

			Intent intent = new Intent();
			intent.setAction("android.intent.action.VIEW");
			Uri content_url = Uri.parse(url);
			intent.setData(content_url);
			startActivity(intent);
			return true;
		}
	};

	// 注入js函数监听
	private void addImageClickListner(WebView webView) {

		StringBuilder sBodyClickJs = new StringBuilder();
		sBodyClickJs.append("javascript:(function(){");
		sBodyClickJs
				.append("var objs = document.getElementsByTagName(\"body\"); ");
		sBodyClickJs.append("for(var i=0;i<objs.length;i++)  ");
		sBodyClickJs.append("{");
		sBodyClickJs.append("    objs[i].onclick=function()  ");
		sBodyClickJs.append("    {  ");
		sBodyClickJs
				.append("        window.onBodyClickListner.onBodyClick();  ");
		sBodyClickJs.append("    }  ");
		sBodyClickJs.append("}");
		sBodyClickJs.append("})()");

		webView.loadUrl(sBodyClickJs.toString());
	}

	// js通信接口
	public class JavascriptInterface {

		private Context context;

		public JavascriptInterface(Context context) {
			this.context = context;
		}

		public void onBodyClick() {
			finish();
		}
	}
}
